import type { Router } from 'vue-router'
import { defineStore } from 'pinia'
import { transformAuthRoutesToVueRoutes, transformAuthRoutesToMenuRoutes, getCacheRoutes, getUserInfo } from '@/utils'
import { fetchUserRoutes } from '@/service/api'
import { useTabStore } from './tab'

interface RouteState {
    /** 是否添加过动态路由 */
    isAddedDynamicRoute: boolean
    /** 路由首页name */
    routeHomeName: string
    /** 菜单 */
    menus: Menu.GlobalMenuOption[]
    /** 缓存的路由名称 */
    cacheRoutes: string[]
}

export const useRouteStore = defineStore('route-store', {
    state: (): RouteState => ({
        isAddedDynamicRoute: true,
        routeHomeName: 'home',
        menus: [],
        cacheRoutes: [],
    }),
    actions: {
        /**
         * 初始化动态路由
         * @param router - 路由实例
         */
        async initDynamicRoute(router: Router) {
            const { initHomeTab } = useTabStore()

            const { userId } = getUserInfo()
            if (!userId) return
            const { home, routes } = await fetchUserRoutes(userId)
            if (home) {
                this.routeHomeName = home
                const vueRoutes = transformAuthRoutesToVueRoutes(routes)
                vueRoutes.forEach((route) => {
                    router.addRoute(route)
                })
                this.cacheRoutes = getCacheRoutes(routes)
                this.menus = transformAuthRoutesToMenuRoutes(routes, router.getRoutes())

                initHomeTab(home, router)
                this.isAddedDynamicRoute = true
            }
        },
    },
})
